(function($) {
    /**
     * 分页类构造函数
     *
     * @param {jquery} showArea 页面的显示区域
     * @param {string} requestUrl 分页请求的地址
     * @param {string} tplUrl 前端分页显示用的ejs模板地址
     * @param {?object} requestData 查询所需要的数据
     * @param {function} refreshCallback 刷新表格后的回调函数
     * @constructor
     */
    function Pagination(showArea, requestUrl, tplUrl , requestData, refreshCallback) {
        this._requestUrl = requestUrl;
        this.url = getNoneCacheUrl(requestUrl);
        this.requestData =requestData && typeof (requestData) == 'object' ? requestData : {};
        this.tplEngine = new EJS({url : tplUrl});
        this.showArea = showArea;
        this.currentPage = this._getPageNOInCookie(requestUrl);
        this.refreshCallback = refreshCallback;
        this.xhr = null;
        this._readExtendInCookie();
        this.addEvent();
    }
    Pagination.REQUEST_CURRENT_PAGE = 'currentPage';
    Pagination.COOKIE_NAME_EXTEND_DATA = 'extendData';

    function getCookie(name) {
        var value = null;
        if (typeof ($.cookie) == 'function') {
            value = $.cookie(name);
        }
        return value;
    }

    function setCookie(name,value) {
        if (typeof ($.cookie) == 'function') {
            $.cookie(name, value);
        }
    }

    Pagination.readExtendInCookie = function(requestUrl) {
        var extendCookieName = requestUrl+':' +Pagination.COOKIE_NAME_EXTEND_DATA;
        var extendDataInCookie = getCookie(extendCookieName);
        var extendData = null;
        if (extendDataInCookie) {
            try {
                extendData = JSON.parse(extendDataInCookie);
            } catch (e) {

            }
        }
        return extendData;
    }

    function getNoneCacheUrl(oldUrl) {
//        if (/msie/.test(navigator.userAgent.toLowerCase())) {
            if (oldUrl.indexOf('?') != -1) {
                oldUrl += '&rand=' + Math.random();
            } else {
                oldUrl += '?rand=' + Math.random();
            }
//        }
        return oldUrl;
    }

    Pagination.prototype._getPageNOInCookie = function(requestUrl) {
        var pageNO = 0;
        pageNO = getCookie(requestUrl+':' + Pagination.REQUEST_CURRENT_PAGE);
        pageNO = pageNO > 0 ? pageNO : 1;
        return pageNO;
    }

    Pagination.prototype._readExtendInCookie = function() {
        var extendData = Pagination.readExtendInCookie(this._requestUrl);
        if (extendData && typeof (extendData) == 'object') {
            this.requestData = $.extend(extendData, this.requestData);
        }
    }

    Pagination.prototype._writeExtendToCookie =function (extendData) {
        if (typeof ($.cookie) == 'function') {//写入cookie
            var extendCookieName = this._requestUrl+':' +Pagination.COOKIE_NAME_EXTEND_DATA;
            var extendStr = $.cookie(extendCookieName);
            var extendInCookie = {};

            try {
                if (extendStr) {
                    extendInCookie = JSON.parse(extendStr);
                    $.extend(extendInCookie, extendData);
                    $.cookie(extendCookieName,JSON.stringify(extendInCookie));
                } else {
                    $.cookie(extendCookieName, JSON.stringify(extendData));
                }
            } catch(e) {

            }

        }
    }

    Pagination.prototype._writePageNOToCookie = function(pageNO) {
        setCookie(this._requestUrl+':' + Pagination.REQUEST_CURRENT_PAGE, pageNO);
    }

    Pagination.prototype.updateRequestData = function(extendData) {//查询的时候，将当前页置为1
        $.extend(this.requestData, extendData);
        this.currentPage = 1;
        this._writeExtendToCookie(extendData);
        this._writePageNOToCookie(1);
    }

    Pagination.prototype.resetRequestData = function(requestData) {
        this.requestData =requestData && typeof (requestData) == 'object' ? requestData : {};
        this._writeExtendToCookie(requestData);
        this.currentPage = 1;
        this._writePageNOToCookie(1);
    }

    Pagination.prototype.resetShowArea = function(showArea) {
        this.showArea = showArea;
    }

    Pagination.prototype.setRequestUrl = function(url) {
        this.url = getNoneCacheUrl(url);
    }

    Pagination.prototype.setTplUrl = function(url) {
        this.tplEngine = new EJS({url : url});
    }

    Pagination.prototype.addEvent = function() {
        var self = this;
        $(document).on('click', 'a.prevPage,a.pageNormal,a.nextPage', function() {
            var pageNow = parseInt($(this).attr('pagenum'));
            if (pageNow > 0) {
                self.currentPage = pageNow;
                self.loadData();
                self._writePageNOToCookie(pageNow);
            }

            return false;
        });

    }

    var showPage = function(page) {
        var pageInnerHtml = "";
        if(!page.totalPage || page.totalPage<2){      //没有分页

        } else {
            pageInnerHtml += "<ul>";
            if (page.currentPageNo == 1) {
                pageInnerHtml += '<li><span   class="prevPage">上一页</span></li>';
            } else {
                pageInnerHtml += '<li><a href="" pagenum="' + page.prevPage + '" class="prevPage">上一页</a></li>';
            }

            if(page.startIndex>3){
                pageInnerHtml += '<li><a pagenum="1" class="pageNormal" href="">1</a></li>';
                pageInnerHtml += '<li><a pagenum="2" class="pageNormal" href="">2</a></li>';
                pageInnerHtml += "<li><a href='#'>...</a></li>";
            }
            for(var i=page.startIndex;i<=page.endIndex; i++){
                var str = i;
                if(page.currentPageNo == i){
                    str = '[' + i + ']';
                    pageInnerHtml += '<li><span>' + str + '</a></li>';
                } else {
                    pageInnerHtml += '<li><a pagenum="' + i + '" class="pageNormal" href="">' + str + '</a></li>';
                }

            }
            if(page.endIndex < page.totalPage){
                pageInnerHtml += '<li><span class="pageNormal">...</span></li>';
            }
            if (page.currentPageNo == page.totalPage) {
                pageInnerHtml += '<li><span  class="nextPage">下一页</span></li>';
            } else {
                pageInnerHtml += '<li><a pagenum="' + page.nextPage + '" href="" class="nextPage">下一页</a></li>';
            }

            pageInnerHtml += "</ul> ";
        }

        $(".showPagination").html(pageInnerHtml);
    }
    /**
     * 加载分页数据，后台返回的JSON数据格式为：
     * {
     *     code{number} : 返回码（0代表成功）
     *     msg{string|undefind} : 出错信息
     *     page{object|undefind} : 分页数据
     *     {
     *         data{array} : 分页具体数据
     *         ...其它与页码相关的数据
     *     }
     * }
     */
    Pagination.prototype.loadData = function() {
        this.requestData[Pagination.REQUEST_CURRENT_PAGE] =  this.currentPage;

        var self = this;
        this.showArea.html('');
        if(this.xhr && this.xhr.readyState != 4){
            this.xhr.abort();
        }
        this.xhr = $.get(this.url, this.requestData, function(result) {
            if (result.code != 0) {
                  if (result.msg) {
                      alert(result.msg);
                  } else {
                      alert('服务器异常');
                  }
            } else {
                //显示数据
                var content = self.tplEngine.render(result.page);
                    if (content) {
                    self.showArea.html(content);
                    self.showArea.trigger(Pagination.EVENT_LOAD_DATA_COMPLATE);
                    if (typeof (self.refreshCallback) == 'function') {
                        (self.refreshCallback)();
                    }
                }
                if (result.page && !result.page.disablePage) {
                    //显示页码
                    showPage(result.page);
                }
            }
        },'json');
    }

    Pagination.EVENT_LOAD_DATA_COMPLATE = 'loadDataCompelete';

    $.extend({Pagination : Pagination});

})(jQuery);
